/*
 * Copyright 2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.influxdb;

import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import org.influxdb.annotation.Column;
import org.influxdb.annotation.TimeColumn;

import lombok.Data;

@Data
class ColumnMeta {
	private final PropertyDescriptor propertyDescriptor;
	private final Field field;
	private final String name;
	private final boolean tag;
	private final boolean time;
	private final TimeUnit timeUnit;
	private final boolean numeric;

	static ColumnMeta of(Field field, PropertyDescriptor propertyDescriptor) {
		return new ColumnMeta(field, propertyDescriptor);
	}

	public ColumnMeta(Field field, PropertyDescriptor propertyDescriptor) {
		this.field = field;
		this.propertyDescriptor = propertyDescriptor;
		this.numeric = Number.class.isAssignableFrom(field.getType());
		Column column = getAnnotation(Column.class);
		this.name = column != null ? column.name() : field.getName();
		this.tag = column != null ? column.tag() : false;
		TimeColumn timeColumn = getAnnotation(TimeColumn.class);
		if (timeColumn != null) {
			timeUnit = timeColumn.timeUnit();
			time = true;
		} else {
			timeUnit = TimeUnit.MILLISECONDS;
			time = false;
		}
	}

	private <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
		T annotation = null;
		if (annotation == null && propertyDescriptor != null) {
			Method read = propertyDescriptor.getReadMethod();
			annotation = read != null ? read.getAnnotation(annotationClass) : null;
		}
		if (annotation == null && propertyDescriptor != null) {
			Method method = propertyDescriptor.getWriteMethod();
			annotation = method != null ? method.getAnnotation(annotationClass) : null;
		}
		if (annotation == null) {
			annotation = field.getAnnotation(annotationClass);
		}
		return annotation;
	}
}
